import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.regex.*;

public class MarkdownImageProcessor {
  private static final String BASE_DIR = "F:\\gitee\\personal-blog-document";
  private static final String MARKDOWN_DIR = BASE_DIR + "\\markdown";
  private static final String IMAGE_BASE_DIR = BASE_DIR + "\\image";

  public static void main(String[] args) {
    try {
      processMarkdownFiles();
      System.out.println("图片处理完成！");
    } catch (IOException e) {
      System.err.println("处理失败: " + e.getMessage());
      e.printStackTrace();
    }
  }

  private static void processMarkdownFiles() throws IOException {
    Files.createDirectories(Paths.get(IMAGE_BASE_DIR));

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(MARKDOWN_DIR), "*.md")) {
      for (Path mdFile : stream) {
        System.out.println("处理文件: " + mdFile.getFileName());
        processSingleMarkdownFile(mdFile);
      }
    }
  }

  private static void processSingleMarkdownFile(Path mdFile) throws IOException {
    String content = new String(Files.readAllBytes(mdFile), StandardCharsets.UTF_8);
    String fileName = mdFile.getFileName().toString().replaceFirst("[.][^.]+$", "");
    Path imageDir = Paths.get(IMAGE_BASE_DIR, fileName);
    Files.createDirectories(imageDir);

    Pattern pattern = Pattern.compile("!\\[(.*?)\\]\\((.*?)\\)");
    Matcher matcher = pattern.matcher(content);
    Map<String, String> replacements = new HashMap<>();

    while (matcher.find()) {
      String altText = matcher.group(1);
      String imageUrl = matcher.group(2);

      if (imageUrl.startsWith("http")) {
        try {
          // 关键修改点：使用../前缀的相对路径
          String localPath = downloadImage(imageUrl, imageDir);
          String imageName = Paths.get(localPath).getFileName().toString();
          String newPath = "../image/" + fileName + "/" + imageName;

          replacements.put(
              matcher.group(0),
              "![" + altText + "](" + newPath.replace("\\", "/") + ")"
          );
        } catch (Exception e) {
          System.err.println("下载失败: " + imageUrl + " - " + e.getMessage());
        }
      }
    }

    for (Map.Entry<String, String> entry : replacements.entrySet()) {
      content = content.replace(entry.getKey(), entry.getValue());
    }

    Files.write(mdFile, content.getBytes(StandardCharsets.UTF_8));
  }

  private static String downloadImage(String imageUrl, Path targetDir) throws IOException {
    String fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);
    if (fileName.contains("?")) fileName = fileName.substring(0, fileName.indexOf('?'));

    Path targetFile = targetDir.resolve(fileName);

    try (InputStream in = new URL(imageUrl).openStream()) {
      Files.copy(in, targetFile, StandardCopyOption.REPLACE_EXISTING);
    }

    return targetFile.toString();
  }
}
